package cn.tedu.tmall.admin.content.handler;

import cn.tedu.tmall.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理运行时异常
     * @param e 运行时异常
     * @return JsonResult
     */
    @ExceptionHandler
    public JsonResult handleRuntimeException(RuntimeException e){
        log.debug("运行时异常信息:{}",e.getMessage());
        return JsonResult.fail(e.getMessage());
    }

    /**
     * 处理多条异常
     */
    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //接收多个异常
        List<FieldError> errors = e.getFieldErrors();
        //连接成字符串
        StringBuilder allMessage = new StringBuilder();
        for (FieldError error : errors) {
            allMessage.append(error.getDefaultMessage()).append("|");
        }
        //去除最后的分隔符
        String str = allMessage.delete(allMessage.lastIndexOf("|"), allMessage.length()).toString();
        log.debug("数据校验异常信息:{}",str);
        return JsonResult.fail(str);
    }
}
